# 使用TimedJSONWebSignatureSerializer可以生成带有有效期的token
from itsdangerous import BadData
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings
from . import constants


def generate_save_user_token(openid):
    """
    生成保存用户数据的token,对openid进行加密
    :param openid: 用户的openid
    :return: token
    """
    # 创建序列化器 (加盐秘钥, 时间戳过期时间)
    serializer = Serializer(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
    data = {'openid': openid}
    # 进行序列化和签名加密
    token = serializer.dumps(data)  # 返回bytes类型token

    return token.decode()  # 因为最后存入浏览器端所以要解码


def check_save_user_token(access_token):
    """
    检验保存用户数据的token
    :param access_token: token
    :return: openid or None
    """
    serializer = Serializer(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
    try:
        data = serializer.loads(access_token)
    except BadData:
        return None
    else:
        return data.get('openid')
